using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Data.Core;
using Avalonia.Data.Core.Plugins;
using Avalonia.Markup.Xaml;
using JGSY.AI.DesktopUI.Services;
using JGSY.AI.DesktopUI.ViewModels;
using JGSY.AI.DesktopUI.Views;
using Live.Avalonia;
using System;
using System.Diagnostics;
using System.Linq;

namespace JGSY.AI.DesktopUI;

public partial class App : Application, ILiveView
{
    public static IThemeService ThemeService { get; private set; } = null!;
    public override void Initialize()
    {
        AvaloniaXamlLoader.Load(this);
        
        // 初始化主题服务
        ThemeService = new ThemeService();
        InitializeThemes();
    }

    public override void OnFrameworkInitializationCompleted()
    {
        if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
        {
            // Avoid duplicate validations from both Avalonia and the CommunityToolkit. 
            // More info: https://docs.avaloniaui.net/docs/guides/development-guides/data-validation#manage-validationplugins
            DisableAvaloniaDataAnnotationValidation();

#if DEBUG
            // Debug 下启用 Live.Avalonia 热更新主机
            var host = new LiveViewHost(this, msg => Debug.WriteLine($"[Live.Avalonia] {msg}"));
            host.StartWatchingSourceFilesForHotReloading();
            desktop.MainWindow = host;
#else
            // Release/非调试模式正常启动窗口
            var mainWindowViewModel = new MainWindowViewModel();
            desktop.MainWindow = new MainWindow
            {
                DataContext = mainWindowViewModel,
            };
#endif

            // 应用保存的主题
            ThemeService.ApplyTheme(ThemeService.CurrentTheme);
        }

        base.OnFrameworkInitializationCompleted();
    }

    // ILiveView: 返回嵌入到 LiveViewHost 窗口中的内容
    public object CreateView(Window window)
    {
        // 保持应用状态：复用 Window 的 DataContext
        if (window.DataContext is null)
        {
            window.DataContext = new MainWindowViewModel();
        }

        // 实例化 MainWindow，抽出其内容作为可重载视图
        var tempWindow = new MainWindow();
        // 取出内容并与 host window 的 DataContext 关联
        var content = tempWindow.Content as Control;
        // 解除与临时窗口的父子关系，避免“Control already has a parent”
        tempWindow.Content = null;

        if (content is not null)
        {
            content.DataContext = window.DataContext;
            return content;
        }

        // 兜底
        return new TextBlock { Text = "无法加载主界面内容" };
    }

    private void InitializeThemes()
    {
        // 主题服务会自动加载保存的主题，这里只需要设置默认资源
        ThemeService.ApplyTheme(ThemeService.CurrentTheme);
    }

    private void DisableAvaloniaDataAnnotationValidation()
    {
        // Get an array of plugins to remove
        var dataValidationPluginsToRemove =
            BindingPlugins.DataValidators.OfType<DataAnnotationsValidationPlugin>().ToArray();

        // remove each entry found
        foreach (var plugin in dataValidationPluginsToRemove)
        {
            BindingPlugins.DataValidators.Remove(plugin);
        }
    }
}
